# 在没有*的情况下，判断s是否能被p匹配的转移方程
# dp[i][j]表示s的前i个字符和p的前j个
# i从1开始，j从1开始
# dp[i][j] = dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.')
# 加入*的情况
# 当p[j-1] == '*' 时，考虑三种情况：
# 1. 匹配0次：此时需要 dp[i][j-2] 为 true，返回 true。
# 2. 匹配1次：此时需要 dp[i-1][j-2] && (s[i-1] == p[j-2] || p[j-2] == '.')
# 3. 匹配多次：此时需要 dp[i-1][j] && (s[i-1] == p[j-2] || p[j-2] == '.')


class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        m, n = len(s), len(p)
        dp = [[False] * (n + 1) for _ in range(m + 1)]

        # 初始化
        dp[0][0] = True
        # TODO: 初始化 dp[0][j]
        for j in range(1, n + 1):
            if p[j - 1] == "*" and j >= 2:
                dp[0][j] = dp[0][j - 2]
            else:
                dp[0][j] = False

        # 填表

        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if p[j - 1] == "*":
                    match = s[i - 1] == p[j - 2] or p[j - 2] == "."
                    dp[i][j] = (
                        dp[i][j - 2]
                        or (dp[i - 1][j - 2] and match)
                        or (dp[i - 1][j] and match)
                    )
                else:
                    dp[i][j] = dp[i - 1][j - 1] and (
                        s[i - 1] == p[j - 1] or p[j - 1] == "."
                    )
        return dp[m][n]
